package com.polaris.live.widget.refresh

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.annotation.DrawableRes

/**
 * 包含loading、empty、error的view
 *
 * @author Created by lucas on 2023/11/1 21:12
 */
class LoadStateView(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) {

    private var mState: Int = STATE_LOADING

    private val loadingView = LoadingView(context)

    private val emptyView = EmptyView(context)

    private val errorView = ErrorView(context)

    init {
        addView(loadingView)

        emptyView.visibility = GONE
        addView(emptyView)

        errorView.visibility = GONE
        addView(errorView)
    }

    fun setState(state: Int, errorMessage: String? = null) {
        if (mState == state) {
            if (state == STATE_ERROR) {
                errorView.setText(errorMessage ?: "unknown")
            }
            return
        }

        when (state) {
            STATE_LOADING -> {
                loadingView.visibility = VISIBLE
            }
            STATE_ERROR -> {
                errorView.visibility = VISIBLE
                errorView.setText(errorMessage ?: "unknown")
            }
            STATE_EMPTY -> {
                emptyView.visibility = VISIBLE
            }
            STATE_SUCCESS -> {
                visibility = GONE
            }
        }

        when (mState) {
            STATE_LOADING -> {
                loadingView.visibility = GONE
            }
            STATE_ERROR -> {
                errorView.visibility = GONE
            }
            STATE_EMPTY -> {
                emptyView.visibility = GONE
            }
            STATE_SUCCESS -> {
                visibility = VISIBLE
            }
        }

        mState = state
    }

    /**
     * 设置空显示
     */
    fun setEmptyTip(@DrawableRes img: Int, tip: String) {
        emptyView.setEmptyTip(img, tip)
    }

    fun getState(): Int {
        return mState
    }

    fun isLoading(): Boolean {
        return mState == STATE_LOADING
    }

    fun isEmpty(): Boolean {
        return mState == STATE_EMPTY
    }

    fun isError(): Boolean {
        return mState == STATE_ERROR
    }

    fun isSuccess(): Boolean {
        return mState == STATE_SUCCESS
    }

    companion object {

        const val STATE_LOADING = 0
        const val STATE_ERROR = 1
        const val STATE_EMPTY = 2
        const val STATE_SUCCESS = 3
    }
}